Risipa de key_press | Programare

Programare .Net | Tehnici de programare | Tutoriale | Lectii si exemple

Risipa de key_press | Programare - Programare .Net | Tehnici de programare | Tutoriale | Lectii si exemple

Sirul lui Fibonacci

Să se determine primii n termeni ai şirului lui Fibonacci.

Analiza Programului
In sirul de numere Fibonacci, fiecare numar reprezinta suma a doua numere anterioare. Astfel, șirul incepe cu 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 etc.
Vom utiliza 3 variabile. In firstNumber si secondNumber vom retine doi membri Fibonacci consecutivi. Acestia vor fi initializati cu primii termeni ai sirului.

In fNumber vom calcula termenul urmator.

Rezolvarea in C#


using System;

namespace _25
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Introduceti numarul termenilor");
            int n = int.Parse(Console.ReadLine());
            int firstNumber = 1, secondNumber = 1, fNumber;

            Console.WriteLine("Fb(0) = 1 ");
            Console.WriteLine("Fb(1) = 1 ");
            
            for (int i = 2; i < n; i++)
            {
                fNumber= firstNumber + secondNumber;
                secondNumber = firstNumber;
                firstNumber = fNumber;

                Console.WriteLine("Fibo ({0}) = {1} ", i, fNumber);
            }

            Console.Read();
        }
    }
}

Rezolvarea in C++


//the header conio, which include library functions for performing "console input and output"
#include <conio.h>
//the header iostream, which supports the C++ I/O system
#include <iostream>
//tells the compiler to use the std namespace
using namespace std;

//begin program execution
int main()
{
    int n, firstNumber = 1, secondNumber = 1, fNumber;
    cout<<"Introduceti numarul termenilor :";
    cin>>n;

    cout<<"Fb(0) = 1"<<endl;
    cout<<"Fb(1) = 1"<<endl;

    for (int i = 2; i < n; i ++)
    {
        fNumber = firstNumber + secondNumber;
        secondNumber = firstNumber;
        firstNumber = fNumber;

        cout<<"Fb("<<i<<") = " <<fNumber<<endl;
    }

    return 0;
}
Category: Uncategorized

Your email address will not be published. Required fields are marked *

*